<template>
  <div class="main">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>书籍管理</el-breadcrumb-item>
      <el-breadcrumb-item>全部书籍</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            clearable
            placeholder="请输入内容"
            v-model="queryInfo.queryname"
            @clear="getSongList"
            class="input-with-select"
          >
            <el-button
              @click="getSongList"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="addDialogVisible = true" type="primary"
            >添加书籍</el-button
          >
        </el-col>
      </el-row>

      <!-- 添加书籍对话框 -->
      <el-dialog
        title="添加书籍"
        @close="addDialogClosed"
        :visible.sync="addDialogVisible"
        width="50%"
      >
        <!-- 内容主体区 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="书籍名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="artist">
            <el-input v-model="addForm.artist"></el-input>
          </el-form-item>
          <el-form-item label="书籍图片" prop="pic">
            <!-- <el-input v-model="addForm.pic"></el-input> -->
            <el-upload
              action="http://localhost:3000/api/admin/upload"
              list-type="picture-card"
              accept="image"
              :limit="1"
              :on-remove="handleRemove"
              :on-success="imgUploadSuccess"
              :on-exceed="uploadExceed"
              :before-upload="uploadBefore"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="uploadDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="书籍文件" prop="musicurl">
            <el-upload
              action="http://localhost:3000/api/admin/upload"
              multiple
              :limit="1"
              :file-list="songFileList"
              :on-exceed="uploadExceed"
              :on-success="songUploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传音频文件
              </div>
            </el-upload>
            <!-- <el-input v-model="addForm.musicurl"></el-input> -->
          </el-form-item>
          <el-form-item label="简介" prop="introduction">
            <el-input
              :rows="2"
              type="textarea"
              placeholder="请输入内容"
              v-model="addForm.introduction"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSong">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改书籍对话框 -->
      <el-dialog
        title="修改书籍"
        @close="editDialogClosed"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <!-- 内容主体区 -->
        <el-form
          :model="editForm"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="80px"
        >
          <el-form-item label="书籍名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="artist">
            <el-input v-model="editForm.artist"></el-input>
          </el-form-item>
          <el-form-item label="书籍图片" prop="pic">
            <el-upload
              action="http://localhost:3000/api/admin/upload"
              :file-list="editImgList"
              :on-success="editImgUploadSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
            <!-- <el-input v-model="editForm.pic"></el-input> -->
          </el-form-item>
          <el-form-item label="书籍文件" prop="musicurl">
            <el-upload
              action="http://localhost:3000/api/admin/upload"
              multiple
              :limit="1"
              :file-list="editSongList"
              :on-success="editSongUploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传音频文件
              </div>
            </el-upload>
            <!-- <el-input v-model="editForm.musicurl"></el-input> -->
          </el-form-item>
          <el-form-item label="简介" prop="introduction">
            <el-input
              :rows="2"
              type="textarea"
              placeholder="请输入内容"
              v-model="editForm.introduction"
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSongInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 书籍列表区 -->
      <el-table
        class="box"
        :data="allSongList"
        style="width: 100%"
        @cell-click="palySong"
        border
      >
        <el-table-column prop="id" align="center" label="id" width="45">
        </el-table-column>
        <el-table-column prop="pic" align="center" sortable label="图片">
          <template slot-scope="scope">
            <div>
              <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.pic"
                :preview-src-list="[scope.row.pic]"
              >
              </el-image>
              <!-- <img style="width:50px;height:50px" :src="scope.row.pic" alt="" /> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="书名">
        </el-table-column>
        <el-table-column prop="artist" align="center" label="作者">
        </el-table-column>
        <!-- <el-table-column prop="album" label="专辑"> </el-table-column> -->
        <!-- <el-table-column prop="songTimeMinutes" sortable label="时长">
        </el-table-column> -->
        <el-table-column
          prop="musicurl"
          align="center"
          sortable
          label="音频文件"
        >
        </el-table-column>
        <!-- <el-table-column prop="score100" sortable label="热度">
        </el-table-column> -->
        <el-table-column
          prop="introduction"
          show-overflow-tooltip
          sortable
          label="简介"
        >
        </el-table-column>
        <!-- <el-table-column prop="hasLossless" label="音质">
          <template slot-scope="scope">
            <span
              :class="scope.row.hasLossless == 'true' ? 'wusun' : 'chaopin'"
            >
              {{ scope.row.hasLossless == 'true' ? '无损' : '超品' }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="操作" width="145px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              @click="showEditDialog(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="removeSongById(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import $ from 'jquery'
export default {
  data() {
    return {
      // 编辑上传文件列表
      editSongList: [],
      // 编辑上传图片列表
      editImgList: [],
      // 上传书籍文件
      songFileList: [],
      dialogImageUrl: '',
      uploadDialogVisible: false,
      queryInfo: {
        queryname: '',
        pagenum: 1,
        pagesize: 5
      },
      allSongList: [],
      total: 0,
      // 控制添加对话框显隐
      addDialogVisible: false,
      // 添加书籍表单数据
      addForm: {
        name: '',
        artist: '',
        pic: '',
        musicurl: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入书籍名称', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在3~20', trigger: 'blur' }
        ],
        artist: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在3~20', trigger: 'blur' }
        ],
        pic: [
          { required: true, message: '请输入书籍图片', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在3~20', trigger: 'blur' }
        ],
        musicurl: [
          { required: true, message: '请输入书籍文件路径', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在3~20', trigger: 'blur' }
        ]
      },
      // 控制编辑对话框显隐
      editDialogVisible: false,
      // 查询到的书籍信息对象
      editForm: {}
    }
  },
  mounted: function() {
    // this.getSearchSongTableData()
    $('.el-table__body-wrapper').niceScroll({ cursorcolor: '#EBEEF5' })
    this.getSongList()
  },
  methods: {
    // 书籍上传成功
    editSongUploadSuccess(response, file, fileList) {
      if (response.status !== true) {
        return this.$message.error('上传失败')
      }
      this.editForm.musicurl = response.url
    },
    // 图片上传成功
    editImgUploadSuccess(response, file, fileList) {
      // console.log(response)
      if (response.status !== true) {
        return this.$message.error('上传失败')
      }
      this.editForm.pic = response.url
      // console.log(this.addForm.pic)
    },
    // 书籍上传成功
    songUploadSuccess(response, file, fileList) {
      if (response.status !== true) {
        return this.$message.error('上传失败')
      }
      this.addForm.musicurl = response.url
    },
    // 图片上传成功
    imgUploadSuccess(response, file, fileList) {
      // console.log(response)
      if (response.status !== true) {
        return this.$message.error('上传失败')
      }
      this.addForm.pic = response.url
      // console.log(this.addForm.pic)
    },
    // 文件超出个数限制时的钩子
    uploadExceed(file, fileList) {
      this.$message.error('只能上传一个文件')
    },
    // 上传文件之前的钩子
    uploadBefore(file) {
      var acceptableMime = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']
      if (acceptableMime.indexOf(file.type) !== 1) {
        this.$message({
          type: 'error',
          message: '文件类型错误'
        })
        return false
      }
    },
    // 点击移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },

    // 根据id删除书籍
    removeSongById(id) {
      // 弹窗询问用户是否删除此数据
      this.$confirm('此操作将永久删除该书籍, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.post('api/admin/song/delete', {
            id
          })
          // console.log(res)
          if (res.status !== true) {
            return this.$message({
              type: 'error',
              message: '删除书籍失败'
            })
          }
          this.$message({
            type: 'success',
            message: '删除书籍成功!'
          })
          this.getSongList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 修改书籍信息并提交
    editSongInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return 0
        console.log(valid)
        // 发起修改书籍信息的请求
        const { data: res } = await this.$http.post(
          'api/admin/song/update',
          this.editForm
        )
        if (res.status !== true) {
          this.$message.error('修改书籍失败')
          return
        }
        this.$message.success('修改书籍成功')
        // 隐藏添加书籍对话框
        this.editDialogVisible = false
        // 重新获取书籍列表数据
        this.getSongList()
      })
    },
    // 监听编辑书籍对话框关闭事件
    editDialogClosed: function() {
      console.log('123456')
      this.editSongList = []
      this.editImgList = []
    },
    // 展示编辑书籍对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('api/front/songid', {
        params: { id }
      })
      if (res.status !== true) {
        this.$message.error('获取失败')
        return 0
      }
      // console.log(res.data[0])
      this.editForm = res.data[0]
      this.editImgList = [
        {
          name: this.editForm.pic.slice(this.editForm.pic.lastIndexOf('/') + 1),
          url: this.editForm.pic
        }
      ]
      this.editSongList = [
        {
          name: this.editForm.musicurl.slice(
            this.editForm.musicurl.lastIndexOf('/') + 1
          ),
          url: this.editForm.musicurl
        }
      ]
      this.editDialogVisible = true
    },
    // 点击按钮，添加书籍
    addSong: function() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return 0
        // console.log(valid)
        const { data: res } = await this.$http.post(
          'api/admin/addsong',
          this.addForm
        )
        if (res.status !== true) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getSongList()
      })
    },
    // 监听添加书籍对话框关闭事件
    addDialogClosed: function() {
      this.$refs.addFormRef.resetFields()
    },
    // 获取书籍列表
    getSongList: async function() {
      const { data: res } = await this.$http.get('api/front/songs', {
        params: this.queryInfo
      })
      console.log(res)
      // 如果是删除第一条，删除后会获取失败，页数-1，重新获取
      if (res.status !== true && this.queryInfo.pagenum > 1) {
        this.queryInfo.pagenum = this.queryInfo.pagenum - 1
        this.getSongList()
        return 0
      }
      this.allSongList = res.data.songs
      this.total = res.data.total
    },
    // 每页条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getSongList()
    },
    // 当前页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getSongList()
    },
    // 点击播放
    palySong(row, column, event, cell) {
      this.$emit('songObj', row)
    }
  },
  watch: {
    $route(to, from) {
      this.getSearchSongTableData()
    }
  }
}
</script>

<style lang="less" scoped>
.wusun {
  // margin-left: 5px;
  padding: 2px;
  flex-shrink: 0;
  font-size: 12px;
  color: #e6b86d;
  cursor: pointer;
  border: #e6b86d solid 1px;
  border-radius: 2px;
}

.chaopin {
  // margin-left: 5px;
  padding: 2px;
  flex-shrink: 0;
  font-size: 12px;
  color: #7c8db5;
  cursor: pointer;
  border: #7c8db5 solid 1px;
  border-radius: 2px;
}
</style>
